package com.koron.beetl;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map.Entry;

import org.beetl.core.Configuration;
import org.beetl.core.Format;
import org.beetl.core.Function;
import org.beetl.core.GroupTemplate;
import org.beetl.core.Template;
import org.beetl.core.resource.StringTemplateResourceLoader;

public class BeetlTool {
	private HashMap<String, Object> map = new HashMap<>();
	private HashMap<String, Format> format = new HashMap<>();
	private HashMap<String, Function> function = new HashMap<>();
	private Configuration cfg = null;

	private BeetlTool() {
		try {
			cfg = Configuration.defaultConfiguration();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static BeetlTool getIntance() {
		BeetlTool tool = new BeetlTool();
		return tool;
	}

	public Object put(String key, Object value) {
		return map.put(key, value);
	}

	public Object remove(Object key) {
		return map.remove(key);
	}

	public void clear() {
		map.clear();
	}

	public Object putFormat(String key, Format value) {
		return format.put(key, value);
	}

	public Object removeFormat(String key) {
		return format.remove(key);
	}

	public void clearFormat() {
		format.clear();
	}

	public Object putFunction(String key, Function value) {
		return function.put(key, value);
	}

	public Object remove(String key) {
		return function.remove(key);
	}

	public void clearFunction() {
		function.clear();
	}

	public Configuration getCfg() {
		return cfg;
	}

	public void setCfg(Configuration cfg) {
		this.cfg = cfg;
	}

	public String render(String str) {
		StringTemplateResourceLoader resourceLoader = new StringTemplateResourceLoader();
		GroupTemplate gt = new GroupTemplate(resourceLoader, cfg);
		for (Entry<String, Function> ent : function.entrySet()) {
			gt.registerFunction(ent.getKey(), ent.getValue());
		}
		for (Entry<String, Format> ent : format.entrySet()) {
			gt.registerFormat(ent.getKey(), ent.getValue());
		}

		Template t = gt.getTemplate(str);
		for (Entry<String, Object> item : map.entrySet()) {
			t.binding(item.getKey(), item.getValue());
		}
		return t.render();
	}
}
